#include "bsp_key.h"
#include "bsp_led.h"
#include "Delay.h"

void KEY_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    NVIC_InitTypeDef NVIC_InitStructure;
    EXTI_InitTypeDef EXTI_InitStructure;

    /* 初始化时钟 */
    RCC_AHB1PeriphClockCmd(KEY1_RCC_CLK, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);

    /* 配置GPIO */
    GPIO_InitStructure.GPIO_Pin  = KEY1_GPIO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
    GPIO_Init(KEY1_GPIO_PORT, &GPIO_InitStructure);

    /* 配置外部中断 */
    SYSCFG_EXTILineConfig(KEY1_PORT_SRC, EXTI_PinSource0);
    EXTI_InitStructure.EXTI_Line    = KEY1_LINE;
    EXTI_InitStructure.EXTI_Mode    = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    /* 配置NVIC */
    NVIC_InitStructure.NVIC_IRQChannel = KEY1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

extern uint8_t carMode;
extern uint8_t carRun;
extern uint8_t motor_stop;
/**************************************** 中断回调函数 ****************************************/
void KEY1_IRQHandler(void)
{
    if (EXTI_GetITStatus(KEY1_LINE) != RESET)
    {
        // 按键按下后切换小车运动模式
        carMode = carMode + 1;
        Delay_ms(500);
        carRun = 1;
        motor_stop = 0;
        if (carMode >= 5) {
            carMode = 0;
            carRun = 0;
            motor_stop = 1;
        }
        EXTI_ClearITPendingBit(KEY1_LINE);
    }
}